<template>
  <div>
    <a-dropdown v-model="visible" :trigger="['hover']">
      <div class="header-avatar" style="cursor: pointer">
        <!-- <a-avatar
        style="width: 36px; height: 36px"
        class="avatar"
        :src="user.avatar || require('@/assets/img/profile.png')"
      /> -->
        <div class="img-box">
          <img
            :src="userInfo.headPhotoPath || require('@/assets/img/profile.png')"
          />
        </div>
        <div class="user-box">
          <div class="name textLine">{{ user.subjectName }}</div>
          <div class="company-name textLine">
            {{ userInfo.companyName || '上海米度测控科技有限公司' }}
          </div>
        </div>
        <div style="margin-left: 8px"><a-icon type="down" /></div>
      </div>
      <a-menu :class="['avatar-menu']" slot="overlay">
        <a-menu-item>
          <div class="user-info">
            <div class="img-box">
              <img
                :src="
                  userInfo.headPhotoPath || require('@/assets/img/profile.png')
                "
                alt=""
              />
            </div>
            <div class="text-box">
              <div class="name textLine" :title="userInfo.name">
                {{ userInfo.name }}
              </div>
              <div class="mobile">
                <a-icon type="mobile" />
                {{ userInfo.cellPhone || '' }}
                <a-icon
                  class="edit-mobile"
                  @click="handleBtnEvent('editMobile')"
                  type="form"
                />
              </div>
            </div>
          </div>
        </a-menu-item>
        <!-- <a-menu-item>
          <div class="last-login-time">
            上次登录时间：{{ lastLoginTime || '--' }}
          </div>
        </a-menu-item> -->
        <a-menu-item class="btn-box">
          <a-button icon="file-text" @click="handleBtnEvent('userInfo')">
            基本资料
          </a-button>
          <a-button icon="lock" @click="handleBtnEvent('editPass')">
            修改密码
          </a-button>
          <a-button icon="poweroff" @click="logout">退出</a-button>
        </a-menu-item>
        <a-menu-divider />
        <!-- <a-menu-item @click="handlerSetting">
          <a-icon type="setting" />
          <span>设置</span>
        </a-menu-item> -->
        <a-menu-item>
          <a-input-search
            placeholder="请输入企业名称"
            v-model="searchCompanyName"
            @search="onSearch"
          />
        </a-menu-item>
        <a-menu-item>
          <div class="companyList">
            <div
              :class="item.checked ? 'companyItem checked' : 'companyItem'"
              v-for="(item, index) in subCompany"
              :key="index"
              @click="checkedCompany(index, item)"
            >
              <a-tooltip
                v-if="item.companyName.length >= 18"
                :title="item.companyName"
              >
                <span class="fullName textLine">
                  {{ item.companyName }}
                </span>
              </a-tooltip>
              <div class="fullName textLine" v-else>
                {{ item.companyName }}
              </div>
              <a-icon v-if="item.checked" type="check" />
            </div>
          </div>
        </a-menu-item>
      </a-menu>
    </a-dropdown>
    <edit-form ref="edit" @reloadData="getCompanyName()"></edit-form>
  </div>
</template>

<script>
  import { mapGetters, mapState, mapMutations } from 'vuex'
  import { logout } from '@/services/login/auth'
  import { queryUserByID } from '@/services/login/auth'
  import { queryUserInCompanyList } from '@/services/access/company'
  import EditForm from './components/EditForm.vue'
  import { queryAllPermissionInService } from '@/services/permission/systemPermission'

  export default {
    inject: ['reload'],
    name: 'HeaderAvatar',
    components: {
      EditForm,
    },
    data() {
      return {
        showSetting: false,
        userInfo: {
          companyName: '',
          name: '',
          cellPhone: '',
        },
        checked: 0,
        subCompany: [],
        subLocalCompany: [], //本地备份数据
        visible: false,
        lastLoginTime: undefined, //最后登录时间
        searchCompanyName: undefined,
      }
    },
    //components: {Setting,Drawer},
    computed: {
      ...mapState('setting', [
        'isMobile',
        'theme',
        'layout',
        'footerLinks',
        'copyright',
        'fixedHeader',
        'fixedSideBar',
        'fixedTabs',
        'hideSetting',
        'multiPage',
      ]),
      ...mapGetters('account', ['user']),
    },
    mounted() {
      this.getCompanyName()
      this.queryUserInCompanyList()
    },
    methods: {
      ...mapMutations('account', ['setUser', 'setPermissions']),
      ...mapMutations('setting', [
        'setShowSetDrawer',
        'correctPageMinHeight',
        'setActivatedFirst',
      ]),
      getCompanyName() {
        console.log('this.user-------', this.user)
        const companyID = this.user.companyID
        const userID = this.user.subjectID
        console.log(companyID, userID)
        const params = {
          companyID,
          userID,
        }
        console.log(params)
        queryUserByID(params).then((res) => {
          this.userInfo = res.data.user
          this.lastLoginTime = res.data.lastLoginTime
          console.log(this.userInfo, 'ddddd')
        })
      },
      handleBtnEvent(operateType, rowData = [], isFooter = 1) {
        this.$refs.edit.showModal(operateType, rowData, isFooter)
      },
      logout() {
        let that = this
        that.visible = !that.visible
        that.$confirm({
          title: '确认退出登录？',
          centered: true,
          onOk() {
            logout()
            that.$router.push('/login')
          },
        })
      },
      handlerSetting() {
        this.setShowSetDrawer(true)
      },
      queryUserInCompanyList() {
        queryUserInCompanyList({}).then((res) => {
          console.log('res----------------', res.data)
          const currentUser = JSON.parse(localStorage.getItem('currentUser'))
          console.log('currentUser--------', currentUser)
          res.data.forEach((curr) => {
            curr.checked = false
            if (curr.companyID === this.user.companyID) {
              curr.checked = true
            }
          })
          //当前用户所属企业置顶
          let newArr = JSON.parse(JSON.stringify(res.data))
          let index = newArr.findIndex(
            (curr) => curr.companyID == currentUser.companyID
          )
          let item = JSON.parse(JSON.stringify(newArr[index]))
          newArr.splice(index, 1)
          newArr.unshift(item)

          /* let selectedIndex = newArr.findIndex((curr) => curr.checked)
          let selectedItem = JSON.parse(JSON.stringify(newArr[selectedIndex]))
          let delItem = newArr.splice(1, 1, selectedItem)
          console.log('delItem----------', delItem)
          newArr.push(...delItem)
          newArr.splice(selectedIndex, 1) */

          this.subCompany = newArr
          this.subLocalCompany = newArr
        })
      },
      checkedCompany(index, item) {
        this.subCompany.forEach((curr, i) => {
          curr.checked = false
          if (index == i) {
            curr.checked = true
          }
        })

        this.visible = !this.visible
        let comanyID = item && item.companyID
        this.changePermission(comanyID)
      },
      changePermission(companyID) {
        queryAllPermissionInService({ companyID }).then((res) => {
          let permissions =
            res.data &&
            res.data.map((item) => {
              return item.serviceName + ':' + item.permissionToken
            })
          this.setPermissions(permissions)
          this.setUser(Object.assign({}, this.user, { companyID }))
          //重新加载页面
          this.reload()
          console.log(permissions, 'permissions')
        })
      },
      onSearch(value) {
        console.log(value)
        console.log(this.searchCompanyName)
        /* if (!value) {
          this.subCompany = JSON.parse(JSON.stringify(this.subLocalCompany))
          return
        } */
        this.subCompany = JSON.parse(JSON.stringify(this.subLocalCompany))
        this.subCompany = this.subCompany.filter((item) =>
          item.companyName.includes(value)
        )
      },
    },
  }
</script>

<style lang="less" scoped>
  .user-box {
    line-height: 25px;
  }
  .header-avatar {
    display: inline-flex;
    align-items: center;
    .avatar,
    .name {
      align-self: center;
    }
    .img-box {
      margin-right: 12px;
      img {
        width: 35px;
        height: 35px;
        border-radius: 6px;
        object-fit: cover;
      }
    }
    .avatar {
      margin-right: 8px;
    }
    .name {
      width: 140px;
      font-weight: 500;
      color: #fff;
    }
    .company-name {
      width: 150px;
      font-size: 12px;
      color: #b0b4b9;
    }
  }
  .avatar-menu {
    box-sizing: border-box;
    width: 300px;
    padding: 20px;
    border-radius: 4px;
    box-shadow: 0 0 10px 0 rgba(0, 0, 0, 0.1);
  }
  .user-info {
    display: flex;
    align-items: center;
    .img-box {
      margin-right: 12px;
      img {
        width: 50px;
        height: 50px;
        border-radius: 6px;
        object-fit: cover;
      }
    }
    .text-box {
      .name {
        width: 150px;
        font-weight: 500;
        color: #333;
      }
      .mobile {
        color: #818f9b;
        .edit-mobile {
          color: @primary-color;
        }
      }
    }
  }
  .last-login-time {
    font-size: 12px;
    color: #818f9b;
  }
  .btn-box {
    .ant-btn {
      padding: 0;
      margin-right: 24px;
      color: #818f9b;
      border: none;
      &:last-child {
        margin-right: 0;
      }
    }
  }
  .ant-dropdown-menu-item,
  .ant-dropdown-menu-submenu-title {
    padding: 5px 0;
  }
  .ant-dropdown-menu-item:hover,
  .ant-dropdown-menu-submenu-title:hover {
    background-color: #fff;
  }
  .setting {
    width: 40px;
    height: 40px;
    font-size: 22px;
    line-height: 40px;
    color: @base-bg-color;
    background-color: @primary-color;
    border-radius: 5px 0 0 5px;
    box-shadow: -2px 0 8px @shadow-color;
  }

  .companyList {
    height: 200px;
    overflow-y: auto;
    .companyItem {
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 10px 20px;
      font-size: 14px;
      color: #818f9b;
      .fullName {
        width: 200px;
      }
      &:hover {
        color: @primary-color;
        background-color: @primary-1;
      }
    }
    .checked {
      color: @primary-color;
      background-color: @primary-1;
    }
  }
</style>
